package com.luyuan.crm.promotion.internal;

import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.proxy.HibernateProxyHelper;

import com.luyuan.crm.member.model.Customer;
import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.model.MemberCoupon;
import com.luyuan.crm.member.model.MemberCouponType;
import com.luyuan.crm.member.model.MemberIntegral;
import com.luyuan.crm.member.model.MemberIntegralReceived;
import com.luyuan.crm.member.model.MemberLevel;
import com.luyuan.crm.member.model.NoAccountCustomer;
import com.luyuan.crm.member.service.MemberCouponService;
import com.luyuan.crm.member.service.MemberIntegralReceivedService;
import com.luyuan.crm.member.service.MemberIntegralService;
import com.luyuan.crm.member.service.MemberService;
import com.luyuan.crm.promotion.MemberIntegralPromotion;
import com.luyuan.crm.promotion.MemberIntegralPromotionService;
import com.luyuan.crm.sale.model.Order;
import com.ruijie.foundation.dao.support.HibernateEntityDao;
import com.ruijie.foundation.dao.support.HibernateUtils;

public class MemberIntegralPromotionServiceImpl extends HibernateEntityDao<MemberIntegral> implements
        MemberIntegralPromotionService {

    private static final Log logger = LogFactory.getLog(MemberIntegralPromotionServiceImpl.class);

    private final static List<MemberIntegralPromotion> MEMBER_LEVEL_PROMOTION = new Vector<MemberIntegralPromotion>();

    private MemberService memberService;

    private MemberIntegralService memberIntegralService;

    private MemberIntegralReceivedService memberIntegralReceivedService;

    private MemberCouponService memberCouponService;

    @Override
    public void updateIntegral(Order order) {
        Member member = null;

        Customer customer = order.getCustomer();
        customer = (Customer) getHibernateTemplate().get(Customer.class, customer.getId());
        Class<?> customerClazz = HibernateProxyHelper.getClassWithoutInitializingProxy(customer);
        if (customerClazz == Member.class) {
            member = (Member) customer;
        }
        else if (customerClazz == NoAccountCustomer.class) {
            member = ((NoAccountCustomer) customer).getAccountHolder();
        }
        else {
            member = memberService.createMember(customer);
        }

        int count = (int) order.getAmount();

        // 总积分
        MemberIntegral memberIntegral = member.getMemberIntegral();
        int totalIntegral = memberIntegral.getTotalIntegral();
        memberIntegral.setTotalIntegral(totalIntegral + count);
        updateIntegral(memberIntegral);

        // 增加推荐积分，送一半积分
        Customer reference = member.getReference();
        if (reference != null && HibernateUtils.resolveRealObject(reference) instanceof Member) {

            memberIntegralService.updateMemberCurrentIntegral(((Member) reference).getMemberIntegral(), count / 2,
                    "推荐会员购物，订单" + order.getId() + "消费获得。");
        }

        // 可用积分
        memberIntegralService.updateMemberCurrentIntegral(member.getMemberIntegral(), count, "订单" + order.getId()
                + "获得。");
        memberService.updateActiveTime(member);

        // 送购物卷
        int couponA = count / 500;
        if (couponA > 0) {
            MemberCoupon memberCoupon = new MemberCoupon();
            memberCoupon.setAmount(couponA * 100);
            memberCoupon.setCouponType(MemberCouponType.A);
            memberCoupon.setMember(member);
            memberCouponService.addMemberCoupon(memberCoupon, "订单" + order.getId() + "获得。");
        }
        if (count > 300) {
            MemberCoupon memberCoupon = new MemberCoupon();
            memberCoupon.setAmount(300);
            memberCoupon.setCouponType(MemberCouponType.B);
            memberCoupon.setMember(member);
            memberCouponService.addMemberCoupon(memberCoupon, "订单" + order.getId() + "获得。");
        }

    }

    @Override
    public void bestowIntegral(Member member, int integral, String remarks) {
        remarks = remarks.replaceAll("#\\{会员姓名\\}", member.getName()).replaceAll("#\\{赠送积分\\}", "" + integral)
                .replaceAll("#\\{会员积分\\}", "" + (member.getMemberIntegral().getCurrentIntegral() + integral));
        // 积分记录
        MemberIntegralReceived memberIntegralReceived = new MemberIntegralReceived();
        memberIntegralReceived.setMember(member);
        memberIntegralReceived.setReceivedTime(new Date());
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.MONTH, 3);
        Date overTime = ca.getTime();
        memberIntegralReceived.setOverTime(overTime);
        memberIntegralReceived.setIntegral(integral);
        memberIntegralReceived.setDescription(remarks);
        memberIntegralReceivedService.addMemberIntegralReceived(memberIntegralReceived);
    }

    private void updateIntegral(MemberIntegral memberIntegral) {
        for (MemberIntegralPromotion promotion : MEMBER_LEVEL_PROMOTION) {
            if (memberIntegral.getTotalIntegral() > promotion.getTotalIntegral()) {
                memberIntegral.setMemberLevel(promotion.getMemberLevel());
                memberIntegral.setDiscount(promotion.getDiscount());
                break;
            }
        }
    }

    public void setMemberIntegralService(MemberIntegralService memberIntegralService) {
        this.memberIntegralService = memberIntegralService;
    }

    public void setMemberIntegralReceivedService(MemberIntegralReceivedService memberIntegralReceivedService) {
        this.memberIntegralReceivedService = memberIntegralReceivedService;
    }

    public void setMemberService(MemberService memberService) {
        this.memberService = memberService;
    }

    @Override
    protected void initDao() throws Exception {
        super.initDao();

        List<MemberIntegralPromotion> levelPromotions = getAll(MemberIntegralPromotion.class);
        MEMBER_LEVEL_PROMOTION.addAll(levelPromotions);
        Collections.sort(MEMBER_LEVEL_PROMOTION);
    }

    @Override
    public void updateMemberLevelPromotion(MemberIntegralPromotion memberLevelPromotion) {
        // 更新折扣
        update("update MemberIntegral set discount = ? where memberLevel = ?",
                new Object[] { memberLevelPromotion.getDiscount(), memberLevelPromotion.getMemberLevel() });

        save(memberLevelPromotion);
        // 更新缓存
        for (MemberIntegralPromotion promotion : MEMBER_LEVEL_PROMOTION) {
            if (promotion.getMemberLevel() == memberLevelPromotion.getMemberLevel()) {
                promotion.setDiscount(memberLevelPromotion.getDiscount());
                promotion.setTotalIntegral(memberLevelPromotion.getTotalIntegral());
                promotion.setBirthIntegral(memberLevelPromotion.getBirthIntegral());
                promotion.setDailyCare(memberLevelPromotion.isDailyCare());
                promotion.setHealthKnowledgeSharing(memberLevelPromotion.isHealthKnowledgeSharing());
                promotion.setOneByOneCare(memberLevelPromotion.isOneByOneCare());
            }
        }
    }

    @Override
    public List<MemberIntegralPromotion> getAllMemberLevelPromotion() {
        return getAll(MemberIntegralPromotion.class, "totalIntegral", true);
    }

    @Override
    public MemberIntegralPromotion findByMemberLevel(MemberLevel memberLevel) {
        return findUniqueBy(MemberIntegralPromotion.class, "memberLevel", memberLevel);
    }

    public void setMemberCouponService(MemberCouponService memberCouponService) {
        this.memberCouponService = memberCouponService;
    }

    @Override
    public void updateMemberLiveness() {
        // MemberLiveness.SLEEP;
        updateBySQL("customer.updateMemberLiveness.sleep");
        // MemberLiveness.COMMONLY;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("liveness", "COMMONLY");
        params.put("count", 1);
        params.put("amount", 1);
        updateBySQL("customer.updateMemberLiveness", params);
        // MemberLiveness.ENLIVEN;
        params.put("liveness", "ENLIVEN");
        params.put("count", 2);
        params.put("amount", 2500);
        updateBySQL("customer.updateMemberLiveness", params);
        // MemberLiveness.POSITIVE;
        params.put("liveness", "POSITIVE");
        params.put("count", 4);
        params.put("amount", 5000);
        updateBySQL("customer.updateMemberLiveness", params);

        logger.info("updateMemberLiveness over! ");
    }
}
